위치 정보
1. 현재 위치 가져오기 (getCurrentLocation)
디바이스의 현재 위치 정보를 한 번만 가져오는 함수예요.
지도에서 사용자 위치를 표시하거나, 가까운 매장을 검색할 때 유용해요.
시그니처
function getCurrentLocation(options: { accuracy: Accuracy }): Promise<Location>;파라미터
- options필수 · object
위치 정보를 가져올 때 사용하는 옵션 객체예요.
- options.accuracy필수 · Accuracy
위치 정보의 정확도 수준이에요. 자세한 값은 아래 Accuracy를 참고해 주세요.
- options.accuracy필수 · Accuracy
반환값
- Promise<Location>
디바이스의 위치 정보가 담긴 객체를 반환해요. 자세한 내용은 아래 Location을 참고해 주세요.
권한 메서드
- getCurrentLocation.getPermission
위치 정보 권한의 현재 상태를 반환해요.
allowed·denied·notDetermined·osPermissionDenied중 하나를 반환해요. - getCurrentLocation.openPermissionDialog
위치 정보 권한을 다시 요청하는 다이얼로그를 표시해요. 허용하면
allowed, 거부하면denied를 반환해요.
에러
권한이 거부된 경우 GetCurrentLocationPermissionError가 발생해요.
class GetCurrentLocationPermissionError extends PermissionError {
constructor();
}예제
import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError } from '@apps-in-toss/web-framework';
async function handleGetCurrentLocation() {
try {
const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
console.log(`위치: ${response.coords.latitude}, ${response.coords.longitude}`);
} catch (error) {
if (error instanceof GetCurrentLocationPermissionError) {
console.log('위치 정보 권한 없음');
}
}
}import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError, Location } from '@apps-in-toss/web-framework';
import { useState } from 'react';
function CurrentPosition() {
const [position, setPosition] = useState<Location | null>(null);
const handlePress = async () => {
try {
const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
setPosition(response);
} catch (error) {
if (error instanceof GetCurrentLocationPermissionError) {
// 위치 정보 권한 없음
}
}
};
return (
<div>
{position ? (
<span>
위치: {position.coords.latitude}, {position.coords.longitude}
</span>
) : (
<span>위치 정보를 아직 가져오지 않았어요</span>
)}
<input type="button" value="현재 위치 가져오기" onClick={handlePress} />
<input
type="button"
value="권한 확인하기"
onClick={async () => alert(await getCurrentLocation.getPermission())}
/>
<input
type="button"
value="권한 요청하기"
onClick={async () => alert(await getCurrentLocation.openPermissionDialog())}
/>
</div>
);
}import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError, Location } from '@apps-in-toss/framework';
import { useState } from 'react';
import { Alert, Button, Text, View } from 'react-native';
function CurrentPosition() {
const [position, setPosition] = useState<Location | null>(null);
const handlePress = async () => {
try {
const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
setPosition(response);
} catch (error) {
if (error instanceof GetCurrentLocationPermissionError) {
// 위치 정보 권한 없음
}
}
};
return (
<View>
{position ? (
<Text>
위치: {position.coords.latitude}, {position.coords.longitude}
</Text>
) : (
<Text>위치 정보를 아직 가져오지 않았어요</Text>
)}
<Button title="현재 위치 가져오기" onPress={handlePress} />
<Button title="권한 확인하기" onPress={async () => Alert.alert(await getCurrentLocation.getPermission())} />
<Button
title="권한 요청하기"
onPress={async () => Alert.alert(await getCurrentLocation.openPermissionDialog())}
/>
</View>
);
}예제 앱 체험하기
apps-in-toss-examples 저장소에서 with-location-once 코드를 내려받거나, 아래 QR 코드를 스캔해 직접 체험해 보세요.
2. 실시간 위치 추적하기 (startUpdateLocation)
위치가 변경될 때마다 콜백을 실행하는 함수예요.
운동 앱에서 이동 거리를 기록하거나 지도에서 위치를 실시간으로 업데이트할 때 사용해요.
반환된 cleanup 함수를 호출하면 추적이 중단돼요.
시그니처
function startUpdateLocation(options: {
onError: (error: unknown) => void;
onEvent: (location: Location) => void;
options: StartUpdateLocationOptions;
}): () => void;파라미터
- onEvent필수 · (location: Location) => void
위치 정보가 변경될 때 호출되는 콜백 함수예요.
- onError필수 · (error: unknown) => void
위치 정보 감지에 실패했을 때 호출되는 콜백 함수예요.
- options필수 · StartUpdateLocationOptions
위치 정보 감지에 필요한 설정 객체예요.
- options.accuracyAccuracy
위치 정확도를 설정해요.
- options.timeIntervalnumber
위치 정보를 업데이트하는 최소 주기예요. 단위는 밀리초(ms)예요.
- options.distanceIntervalnumber
위치 변경 거리를 미터(m) 단위로 설정해요.
- options.accuracyAccuracy
반환값
- () => void
위치 추적을 중단하는 cleanup 함수예요. 컴포넌트 언마운트 시 반드시 호출해 주세요.
권한 메서드
- startUpdateLocation.getPermission
위치 정보 권한의 현재 상태를 반환해요.
- startUpdateLocation.openPermissionDialog
위치 정보 권한을 다시 요청하는 다이얼로그를 표시해요.
예제
import { Accuracy, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/web-framework';
let cleanup;
function handleStartUpdateLocation() {
cleanup?.();
cleanup = startUpdateLocation({
options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 },
onEvent: (location) => {
console.log(`위도: ${location.coords.latitude}, 경도: ${location.coords.longitude}`);
},
onError: (error) => {
if (error instanceof StartUpdateLocationPermissionError) {
console.log('위치 정보 권한 없음');
}
},
});
}
window.addEventListener('pagehide', () => cleanup?.());import {
Accuracy,
Location,
startUpdateLocation,
StartUpdateLocationPermissionError,
} from '@apps-in-toss/web-framework';
import { useCallback, useState } from 'react';
function LocationWatcher() {
const [location, setLocation] = useState<Location | null>(null);
const handlePress = useCallback(() => {
startUpdateLocation({
options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 },
onEvent: (location) => setLocation(location),
onError: (error) => {
if (error instanceof StartUpdateLocationPermissionError) {
// 위치 정보 권한 없음
}
},
});
}, []);
return (
<div>
{location != null && (
<>
<span>위도: {location.coords.latitude}</span>
<span>경도: {location.coords.longitude}</span>
</>
)}
<input type="button" value="위치 추적 시작" onClick={handlePress} />
</div>
);
}import { Accuracy, Location, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/framework';
import { useCallback, useState } from 'react';
import { Button, Text, View } from 'react-native';
function LocationWatcher() {
const [location, setLocation] = useState<Location | null>(null);
const handlePress = useCallback(() => {
startUpdateLocation({
options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 },
onEvent: (location) => setLocation(location),
onError: (error) => {
if (error instanceof StartUpdateLocationPermissionError) {
// 위치 정보 권한 없음
}
},
});
}, []);
return (
<View>
{location != null && (
<>
<Text>위도: {location.coords.latitude}</Text>
<Text>경도: {location.coords.longitude}</Text>
</>
)}
<Button title="위치 추적 시작" onPress={handlePress} />
</View>
);
}예제 앱 체험하기
apps-in-toss-examples 저장소에서 with-location-callback 코드를 내려받거나, 아래 QR 코드를 스캔해 직접 체험해 보세요.
3. 훅으로 위치 사용하기 (useGeolocation)
React Native에서 위치 정보를 React 상태로 사용할 수 있는 Hook이에요.
위치가 변경되면 컴포넌트가 자동으로 리렌더링돼요.
시그니처
function useGeolocation({ accuracy, distanceInterval, timeInterval }: UseGeolocationOptions): Location | null;파라미터
- options필수 · UseGeolocationOptions
위치 정보 감지에 필요한 설정 객체예요.
- options.accuracyAccuracy
위치 정확도를 설정해요. 자세한 값은 아래 Accuracy를 참고해 주세요.
- options.timeIntervalnumber
위치 정보를 업데이트하는 최소 주기예요. 단위는 밀리초(ms)예요.
- options.distanceIntervalnumber
위치 변경 거리를 미터(m) 단위로 설정해요.
- options.accuracyAccuracy
반환값
- Location | null
현재 위치 정보 객체를 반환해요. 위치를 아직 받지 못한 경우
null을 반환해요.
예제
import { useGeolocation, Accuracy } from '@apps-in-toss/framework';
import { Text, View } from 'react-native';
function LocationWatcher() {
const location = useGeolocation({
accuracy: Accuracy.Balanced,
distanceInterval: 10,
timeInterval: 1000,
});
if (location == null) {
return <Text>위치 정보를 가져오는 중이에요...</Text>;
}
return (
<View>
<Text>
위치 정보: {location.coords.latitude}, {location.coords.longitude}
</Text>
</View>
);
}예제 앱 체험하기
apps-in-toss-examples 저장소에서 with-location-tracking 코드를 내려받거나, 아래 QR 코드를 스캔해 직접 체험해 보세요.
타입 · 객체
Accuracy
위치 정확도 수준을 설정하는 enum이에요.
enum Accuracy {
Lowest = 1, // 오차범위 3KM 이내
Low = 2, // 오차범위 1KM 이내
Balanced = 3, // 오차범위 몇 백미터 이내
High = 4, // 오차범위 10M 이내
Highest = 5, // 가장 높은 정확도
BestForNavigation = 6, // 네비게이션을 위한 최고 정확도
}Location
위치 정보를 나타내는 객체예요.
interface Location {
accessLocation?: 'FINE' | 'COARSE'; // Android 전용. FINE: 정확한 위치, COARSE: 대략적인 위치
timestamp: number; // 위치가 업데이트된 시점의 유닉스 타임스탬프
coords: LocationCoords; // 세부 좌표 정보
}LocationCoords
세부 위치 좌표 정보를 나타내는 객체예요.
interface LocationCoords {
latitude: number; // 위도
longitude: number; // 경도
altitude: number; // 높이
accuracy: number; // 위치 정확도
altitudeAccuracy: number; // 고도 정확도
heading: number; // 방향
}
